package cn.wolfcode.luowowo.interceptor;

import cn.wolfcode.luowowo.annotation.RequireLogin;
import cn.wolfcode.luowowo.domain.UserInfo;
import cn.wolfcode.luowowo.redis.redisService.IUserInfoRedisService;
import cn.wolfcode.luowowo.util.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器
 */
@Component
public class CheckLoginInterceptor implements HandlerInterceptor {

    @Autowired
    private IUserInfoRedisService userInfoRedisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            //判断请求方法 是否贴了注解@RequireLogin
            if (handlerMethod.hasMethodAnnotation(RequireLogin.class)) {
                //拦截逻辑实现
                String token = request.getHeader("token");
                UserInfo user = userInfoRedisService.getUserByToken(token);
                if (user == null) {
                    //思考 : 访问页面 还是Json数据
                        response.getWriter().write(JSON.toJSONString(JsonResult.noLogin()));
                    return false;
                }
            }
        }
        //如果没贴@RequireLogin 直接放行
        return true;
    }
}
